package com.suxin.test;

import com.suxin.exception.bussine.RestException;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 * @author Tang
 * @classname ReTryUtils
 * @description [  ]
 * @date 2022/10/12 21:09
 */
@Slf4j
public class ReTryUtils {

    private Integer maxReTryCount = 2;
    private Integer currentCount;

    private ReTryUtils(Integer maxReTryCount) {
        this.maxReTryCount = maxReTryCount;
        this.currentCount = 1;
    }

    public static ReTryUtils create(Integer maxReTryCount) {
        return new ReTryUtils(maxReTryCount);
    }

    public void syncDoTry(Runnable runnable){
        syncTry(runnable, 0);
    }

    private void syncTry(Runnable runnable,int start){
        while (start < currentCount && currentCount <= maxReTryCount) {
            try {
                runnable.run();
                start++;
            } catch (Exception e) {
                log.info("重试:{}次执行！",this.currentCount);
                this.currentCount++;
                syncTry(runnable,start + 1);
            }
        }
    }

    @Resource
    IndexController indexController;

    public void test01(){
        ReTryUtils reTryUtils = ReTryUtils.create(3);
        reTryUtils.syncDoTry(() -> {
            indexController.error();
        });
    }

    public static void main(String[] args) {
        final int[] i = {1};
        ReTryUtils reTryUtils = ReTryUtils.create(3);
        reTryUtils.syncDoTry(() -> {
            if (i[0] == 1) {
                i[0] = i[0] + 1;
                throw new RestException("11");
            }

        });
    }

}
